package common

import (
	"fmt"
	"io/ioutil"
	"path/filepath"
	"strings"
	"time"
)

func spec(mock *Mock) error {
	// File path
	//filePath := "example.txt"

	filePath := filepath.Join(mock.DIR, mock.PKG, mock.PKG, mock.PKG+".spec")

	// Read file content into memory
	//contentBytes, err := os.ReadFile(filePath)
	contentBytes, err := ioutil.ReadFile(filePath)
	if err != nil {
		return err
		//log.Fatalf("failed to read file: %s", err)
	}
	content := string(contentBytes)
	contentLines := strings.Split(content, "\n")

	//auto parse date and target version
	currentTime := time.Now()
	formattedTime := currentTime.Format("Mon Jan 2 2006")
	changelogEntry := fmt.Sprintf("* %s edwardewang <edwardewang@tencent.com> - %s-1\n- Upgrade to %s\n",
		formattedTime, mock.VERSION, mock.VERSION)

	for i, line := range contentLines {
		switch {
		case strings.HasPrefix(line, "Version:"):
			{
				contentLines[i] = "Version: " + mock.VERSION
			}
		case strings.HasPrefix(line, "Release:"):
			{
				contentLines[i] = "Release: 1%{?dist}"
			}
		case strings.HasPrefix(line, "%changelog"):
			{
				// Insert the changelog entry after the %changelog line
				contentLines = append(contentLines[:i+1], append([]string{changelogEntry}, contentLines[i+1:]...)...)
				break
			}
		}
	}
	modifiedContent := strings.Join(contentLines, "\n")

	// Open file for writing
	err = ioutil.WriteFile(filePath, []byte(modifiedContent), 0644)
	if err != nil {
		return err
		//log.Fatalf("failed to write to file: %s", err)
	}
	return nil
}
